"""
综合技术分析器 - 合并RSI反弹和MACD底背离分析
"""

import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')  # 使用非交互式后端，不显示GUI窗口
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import logging
from typing import List, Tuple, Optional, Dict
import warnings
import os
import json
warnings.filterwarnings('ignore')

# 导入自定义模块
from rsi_analyzer import RSIAnalyzer
from divergence_analyzer import DivergenceAnalyzer

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class CombinedTechnicalAnalyzer:
    """综合技术分析器类"""
    
    def __init__(self, 
                 # RSI参数
                 rsi_period: int = 14,
                 rsi_oversold_threshold: float = 30.0,
                 # MACD参数
                 macd_fast_period: int = 12,
                 macd_slow_period: int = 26,
                 macd_signal_period: int = 9,
                 # 底背离检测参数
                 min_distance: int = 5,
                 lookback_window: int = 10,
                 max_divergence_distance: int = 50):
        """
        初始化综合技术分析器
        
        Args:
            rsi_period: RSI计算周期
            rsi_oversold_threshold: RSI超卖阈值
            macd_fast_period: MACD快线周期
            macd_slow_period: MACD慢线周期  
            macd_signal_period: MACD信号线周期
            min_distance: 局部极值点最小间距
            lookback_window: 寻找极值点的回望窗口
            max_divergence_distance: 底背离检测的最大距离
        """
        # 初始化RSI分析器
        self.rsi_analyzer = RSIAnalyzer(
            rsi_period=rsi_period,
            oversold_threshold=rsi_oversold_threshold
        )
        
        # 初始化底背离分析器
        self.divergence_analyzer = DivergenceAnalyzer(
            fast_period=macd_fast_period,
            slow_period=macd_slow_period,
            signal_period=macd_signal_period,
            min_distance=min_distance,
            lookback_window=lookback_window,
            max_divergence_distance=max_divergence_distance
        )
        
        self.rsi_period = rsi_period
        self.rsi_threshold = rsi_oversold_threshold
    
    def analyze_combined_signals(self, 
                                data: pd.DataFrame,
                                price_column: str = 'close',
                                interval: str = '4h') -> Dict:
        """
        执行综合技术分析
        
        Args:
            data: 价格数据DataFrame
            price_column: 用于分析的价格列名
            interval: K线间隔，用于动态调整组合信号容忍度
            
        Returns:
            综合分析结果字典
        """
        logger.info("开始执行综合技术分析...")
        
        # 1. RSI分析
        logger.info("执行RSI反弹分析...")
        data_with_rsi = data.copy()
        data_with_rsi['rsi'] = self.rsi_analyzer.calculate_rsi(data_with_rsi[price_column])
        rsi_signals = self.rsi_analyzer.find_oversold_signals(data_with_rsi)
        
        # 2. 底背离分析
        logger.info("执行MACD底背离分析...")
        divergence_data, divergence_signals = self.divergence_analyzer.detect_bullish_divergence(
            data, price_column
        )
        
        # 3. 合并数据
        combined_data = pd.concat([
            divergence_data,
            data_with_rsi[['rsi']].reindex(divergence_data.index)
        ], axis=1)
        
        # 4. 标记信号
        combined_data['rsi_bounce'] = False
        combined_data['macd_divergence'] = False
        combined_data['combined_signal'] = False
        
        # 标记RSI反弹信号
        if not rsi_signals.empty:
            for idx in rsi_signals.index:
                if idx in combined_data.index:
                    combined_data.loc[idx, 'rsi_bounce'] = True
        
        # 标记底背离信号
        for signal in divergence_signals:
            idx = combined_data.index[signal['current_index']]
            combined_data.loc[idx, 'macd_divergence'] = True
        
        # 标记组合信号（时间接近的RSI和底背离信号）
        self._identify_combined_signals(combined_data, rsi_signals, divergence_signals, interval)
        
        logger.info(f"分析完成：RSI信号{len(rsi_signals)}个，底背离信号{len(divergence_signals)}个")
        
        return {
            'combined_data': combined_data,
            'rsi_signals': rsi_signals,
            'divergence_signals': divergence_signals,
            'rsi_count': len(rsi_signals),
            'divergence_count': len(divergence_signals),
            'combined_signals': self._get_combined_signals(combined_data)
        }
    
    def _identify_combined_signals(self, 
                                  data: pd.DataFrame,
                                  rsi_signals: pd.DataFrame,
                                  divergence_signals: List[Dict],
                                  interval: str = '4h') -> None:
        """
        识别组合信号（RSI反弹和底背离时间接近的信号）
        
        Args:
            data: 合并后的数据
            rsi_signals: RSI反弹信号
            divergence_signals: 底背离信号列表
            interval: K线间隔，用于动态调整容忍度
        """
        if rsi_signals.empty or not divergence_signals:
            return
        
        # 根据K线间隔动态调整容忍度
        interval_to_tolerance = {
            '1m': 1,     # 1分钟：1小时
            '5m': 2,     # 5分钟：2小时
            '15m': 3,    # 15分钟：3小时
            '30m': 4,    # 30分钟：4小时
            '1h': 6,     # 1小时：6小时
            '2h': 12,    # 2小时：12小时
            '4h': 24,    # 4小时：24小时
            '6h': 36,    # 6小时：36小时
            '8h': 48,    # 8小时：48小时
            '12h': 60,   # 12小时：60小时
            '1d': 72,    # 1天：3天
            '3d': 144,   # 3天：6天
            '1w': 168,   # 1周：7天
        }
        
        time_tolerance_hours = interval_to_tolerance.get(interval, 24)
        logger.info(f"根据K线间隔 {interval} 动态调整容忍度为 {time_tolerance_hours} 小时")
        
        tolerance = pd.Timedelta(hours=time_tolerance_hours)
        
        for _, rsi_signal in rsi_signals.iterrows():
            rsi_time = rsi_signal.name
            
            for div_signal in divergence_signals:
                div_time = div_signal['timestamp']
                
                # 检查时间是否接近
                if abs(rsi_time - div_time) <= tolerance:
                    # 标记为组合信号
                    data.loc[rsi_time, 'combined_signal'] = True
                    data.loc[div_time, 'combined_signal'] = True
                    
                    logger.info(f"发现组合信号: RSI反弹({rsi_time}) + 底背离({div_time})")
    
    def _get_combined_signals(self, data: pd.DataFrame) -> pd.DataFrame:
        """获取组合信号数据"""
        return data[data['combined_signal'] == True]
    
    def save_analysis_data(self, 
                          analysis_result: Dict, 
                          symbol: str, 
                          period_days: int,
                          output_dir: str = "output") -> Dict[str, str]:
        """
        保存分析数据到文件
        
        Args:
            analysis_result: 综合分析结果
            symbol: 交易对符号
            period_days: 分析周期天数
            output_dir: 输出目录
            
        Returns:
            保存的文件路径字典
        """
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        base_filename = f"{symbol}_{period_days}days_{timestamp}"
        
        saved_files = {}
        
        try:
            # 1. 保存完整的技术指标数据 (CSV格式)
            data_file = os.path.join(output_dir, f"{base_filename}_full_data.csv")
            full_data = analysis_result['combined_data'].copy()
            
            # 重置索引，将时间索引作为列保存
            full_data_to_save = full_data.reset_index()
            full_data_to_save.to_csv(data_file, index=False, encoding='utf-8-sig')
            saved_files['full_data'] = data_file
            logger.info(f"完整技术指标数据已保存到: {data_file}")
            
            # 2. 保存RSI反弹信号数据 (CSV格式)
            if not analysis_result['rsi_signals'].empty:
                rsi_file = os.path.join(output_dir, f"{base_filename}_rsi_signals.csv")
                rsi_data = analysis_result['rsi_signals'].reset_index()
                rsi_data.to_csv(rsi_file, index=False, encoding='utf-8-sig')
                saved_files['rsi_signals'] = rsi_file
                logger.info(f"RSI反弹信号数据已保存到: {rsi_file}")
            
            # 3. 保存底背离信号数据 (JSON格式，因为包含复杂结构)
            if analysis_result['divergence_signals']:
                div_file = os.path.join(output_dir, f"{base_filename}_divergence_signals.json")
                
                # 转换底背离信号为可序列化的格式
                divergence_data = []
                for div in analysis_result['divergence_signals']:
                    div_copy = div.copy()
                    # 将Timestamp转换为字符串
                    if 'timestamp' in div_copy:
                        div_copy['timestamp'] = div_copy['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
                    # 转换numpy类型为Python原生类型
                    for key, value in div_copy.items():
                        if hasattr(value, 'item'):  # numpy数值类型
                            div_copy[key] = value.item()
                        elif hasattr(value, 'tolist'):  # numpy数组类型
                            div_copy[key] = value.tolist()
                    divergence_data.append(div_copy)
                
                with open(div_file, 'w', encoding='utf-8') as f:
                    json.dump(divergence_data, f, indent=2, ensure_ascii=False)
                saved_files['divergence_signals'] = div_file
                logger.info(f"底背离信号数据已保存到: {div_file}")
            
            # 4. 保存组合信号数据 (CSV格式)
            combined_signals = analysis_result['combined_signals']
            if not combined_signals.empty:
                combined_file = os.path.join(output_dir, f"{base_filename}_combined_signals.csv")
                combined_data = combined_signals.reset_index()
                combined_data.to_csv(combined_file, index=False, encoding='utf-8-sig')
                saved_files['combined_signals'] = combined_file
                logger.info(f"组合信号数据已保存到: {combined_file}")
            
            # 5. 保存分析摘要报告 (TXT格式)
            if 'report' in analysis_result:
                report_file = os.path.join(output_dir, f"{base_filename}_analysis_report.txt")
                with open(report_file, 'w', encoding='utf-8') as f:
                    f.write(analysis_result['report'])
                saved_files['report'] = report_file
                logger.info(f"分析报告已保存到: {report_file}")
            
            # 6. 保存分析元数据 (JSON格式)
            metadata_file = os.path.join(output_dir, f"{base_filename}_metadata.json")
            metadata = {
                'symbol': symbol,
                'period_days': period_days,
                'analysis_timestamp': timestamp,
                'rsi_count': analysis_result['rsi_count'],
                'divergence_count': analysis_result['divergence_count'],
                'combined_signals_count': len(analysis_result['combined_signals']),
                'total_signals': analysis_result['rsi_count'] + analysis_result['divergence_count'],
                'data_range': {
                    'start': analysis_result['combined_data'].index[0].strftime('%Y-%m-%d %H:%M:%S'),
                    'end': analysis_result['combined_data'].index[-1].strftime('%Y-%m-%d %H:%M:%S'),
                    'total_records': len(analysis_result['combined_data'])
                },
                'rsi_parameters': {
                    'period': self.rsi_period,
                    'threshold': self.rsi_threshold
                },
                'macd_parameters': {
                    'fast_period': self.divergence_analyzer.fast_period,
                    'slow_period': self.divergence_analyzer.slow_period,
                    'signal_period': self.divergence_analyzer.signal_period
                },
                'saved_files': saved_files
            }
            
            with open(metadata_file, 'w', encoding='utf-8') as f:
                json.dump(metadata, f, indent=2, ensure_ascii=False)
            saved_files['metadata'] = metadata_file
            logger.info(f"分析元数据已保存到: {metadata_file}")
            
            logger.info(f"✅ 所有分析数据已成功保存到 {output_dir} 目录")
            
        except Exception as e:
            logger.error(f"保存分析数据时出错: {e}")
            raise
        
        return saved_files
    
    def create_combined_visualization(self,
                                    analysis_result: Dict,
                                    symbol: str,
                                    price_column: str = 'close',
                                    save_path: Optional[str] = None) -> None:
        """
        创建综合技术分析可视化图表
        
        Args:
            analysis_result: 综合分析结果
            symbol: 交易对符号
            price_column: 价格列名
            save_path: 图表保存路径（可选）
        """
        data = analysis_result['combined_data']
        rsi_signals = analysis_result['rsi_signals']
        divergence_signals = analysis_result['divergence_signals']
        combined_signals = analysis_result['combined_signals']
        
        # 创建4个子图
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(20, 12))
        fig.suptitle(f'{symbol} 综合技术分析 - RSI反弹 + MACD底背离', fontsize=18, fontweight='bold')
        
        # 子图1：价格走势 + 所有信号
        ax1.plot(data.index, data[price_column], label='收盘价', color='blue', linewidth=1.5)
        
        # 标注K线局部极小值点（重要：按照您的要求）
        price_minima_mask = data['price_minima']
        if price_minima_mask.any():
            price_minima_data = data[price_minima_mask]
            ax1.scatter(price_minima_data.index, price_minima_data[price_column], 
                       color='orange', s=80, marker='v', label='K线局部极小值', zorder=4,
                       edgecolors='black', linewidth=0.5)
            
            # 为每个局部极小值添加数值标注（从原数据读取并转为float，避免显示为0的问题）
            for idx in price_minima_data.index:
                price_value = float(data.loc[idx, price_column])
                ax1.annotate(f'{price_value:.2f}', 
                           xy=(idx, price_value), 
                           xytext=(0, -15), textcoords='offset points',
                           ha='center', va='top',
                           bbox=dict(boxstyle='round,pad=0.2', facecolor='orange', alpha=0.7),
                           fontsize=8)
        
        # 标注RSI反弹信号
        if not rsi_signals.empty:
            ax1.scatter(rsi_signals.index, rsi_signals[price_column], 
                       color='green', s=100, marker='^', label='RSI反弹信号', zorder=5)
        
        # 标注底背离信号
        if divergence_signals:
            div_times = [data.index[sig['current_index']] for sig in divergence_signals]
            div_prices = [sig['current_price'] for sig in divergence_signals]
            ax1.scatter(div_times, div_prices, 
                       color='red', s=120, marker='s', label='底背离信号', zorder=6,
                       edgecolors='darkred', linewidth=1)
        
        # 标注组合信号
        if not combined_signals.empty:
            ax1.scatter(combined_signals.index, combined_signals[price_column], 
                       color='gold', s=150, marker='*', label='组合信号', zorder=7,
                       edgecolors='black', linewidth=1)
        
        ax1.set_title('价格走势与技术信号', fontsize=14, fontweight='bold')
        ax1.set_ylabel('价格 (USDT)', fontsize=12)
        ax1.legend()
        ax1.grid(True, alpha=0.3)
        
        # 子图2：RSI指标
        ax2.plot(data.index, data['rsi'], label='RSI', color='purple', linewidth=1.5)
        ax2.axhline(y=self.rsi_threshold, color='red', linestyle='--', 
                   label=f'超卖线 ({self.rsi_threshold})', alpha=0.7)
        ax2.axhline(y=70, color='green', linestyle='--', 
                   label='超买线 (70)', alpha=0.7)
        ax2.fill_between(data.index, 0, self.rsi_threshold, 
                        alpha=0.2, color='red', label='超卖区域')
        
        # 标注RSI反弹信号
        if not rsi_signals.empty:
            ax2.scatter(rsi_signals.index, rsi_signals['rsi'], 
                       color='green', s=100, marker='^', zorder=5)
            
            # 添加RSI反弹标注
            for idx, row in rsi_signals.iterrows():
                ax2.annotate(f'{row["prev_rsi_value"]:.1f}→{row["rsi"]:.1f}', 
                           xy=(idx, row['rsi']), 
                           xytext=(10, 10), textcoords='offset points',
                           bbox=dict(boxstyle='round,pad=0.3', facecolor='lightgreen', alpha=0.7),
                           fontsize=8)
        
        ax2.set_title('RSI指标与反弹信号', fontsize=14)
        ax2.set_ylabel('RSI值', fontsize=12)
        ax2.set_ylim(0, 100)
        ax2.legend()
        ax2.grid(True, alpha=0.3)
        
        # 子图3：MACD指标
        ax3.plot(data.index, data['macd_line'], label='MACD线', color='blue', linewidth=1.5)
        ax3.plot(data.index, data['signal_line'], label='信号线', color='red', linewidth=1.5)
        ax3.axhline(y=0, color='black', linestyle='-', alpha=0.3)
        
        # 标注MACD局部极小点
        macd_minima_mask = data['macd_minima']
        if macd_minima_mask.any():
            macd_minima_data = data[macd_minima_mask]
            ax3.scatter(macd_minima_data.index, macd_minima_data['macd_line'], 
                       color='orange', s=80, marker='v', label='MACD极小点', zorder=5)
        
        # 标注底背离连接线
        if divergence_signals:
            for div in divergence_signals:
                current_macd_idx = data.index[div['current_macd_idx']]
                previous_macd_idx = data.index[div['previous_macd_idx']]
                
                ax3.plot([previous_macd_idx, current_macd_idx], 
                        [div['previous_macd'], div['current_macd']], 
                        color='red', linestyle='--', alpha=0.7, linewidth=2)
                
                # 添加背离标注
                ax3.annotate(f'背离强度:{div["divergence_strength"]:.1f}', 
                           xy=(current_macd_idx, div['current_macd']), 
                           xytext=(10, 15), textcoords='offset points',
                           bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7),
                           fontsize=8)
        
        ax3.set_title('MACD指标与底背离信号', fontsize=14)
        ax3.set_ylabel('MACD值', fontsize=12)
        ax3.legend()
        ax3.grid(True, alpha=0.3)
        
        # 子图4：MACD柱状图
        colors = ['green' if x >= 0 else 'red' for x in data['macd_histogram']]
        ax4.bar(data.index, data['macd_histogram'], color=colors, alpha=0.6, width=1)
        ax4.axhline(y=0, color='black', linestyle='-', alpha=0.5)
        
        # 标注组合信号时间点
        if not combined_signals.empty:
            for idx in combined_signals.index:
                ax4.axvline(x=idx, color='gold', linestyle=':', alpha=0.8, linewidth=2)
        
        ax4.set_title('MACD柱状图与组合信号', fontsize=14)
        ax4.set_ylabel('MACD柱状图', fontsize=12)
        ax4.set_xlabel('时间', fontsize=12)
        ax4.grid(True, alpha=0.3)
        
        # 统一时间轴格式
        self._format_time_axis([ax1, ax2, ax3, ax4], data)
        
        plt.tight_layout()
        plt.subplots_adjust(top=0.93)  # 为主标题留出空间
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            logger.info(f"综合分析图表已保存到: {save_path}")
        
        plt.show()
    
    def _format_time_axis(self, axes: List, data: pd.DataFrame) -> None:
        """统一格式化时间轴"""
        time_span_hours = (data.index[-1] - data.index[0]).total_seconds() / 3600
        
        for ax in axes:
            if time_span_hours <= 48:  # 2天内
                ax.xaxis.set_major_locator(mdates.HourLocator(interval=6))
                ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M'))
            elif time_span_hours <= 168:  # 7天内
                ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
                ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
            elif time_span_hours <= 720:  # 30天内
                ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
                ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
            else:  # 超过30天
                ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
                ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
            
            ax.tick_params(axis='x', which='major', labelsize=9, rotation=45)
    
    def generate_combined_report(self,
                               analysis_result: Dict,
                               symbol: str,
                               period_days: int) -> str:
        """
        生成综合技术分析报告
        
        Args:
            analysis_result: 综合分析结果
            symbol: 交易对符号
            period_days: 分析周期天数
            
        Returns:
            报告字符串
        """
        rsi_count = analysis_result['rsi_count']
        divergence_count = analysis_result['divergence_count']
        combined_count = len(analysis_result['combined_signals'])
        
        report = f"""
==================== 综合技术分析报告 ====================
交易对: {symbol}
分析周期: {period_days} 天
RSI参数: 周期{self.rsi_period}, 超卖阈值{self.rsi_threshold}
MACD参数: 快线{self.divergence_analyzer.fast_period}, 慢线{self.divergence_analyzer.slow_period}, 信号线{self.divergence_analyzer.signal_period}

================= 信号统计 =================
RSI反弹信号: {rsi_count} 个
MACD底背离信号: {divergence_count} 个
组合信号: {combined_count} 个
总信号数: {rsi_count + divergence_count} 个

================= 信号强度分析 =================
"""
        
        if rsi_count > 0:
            rsi_signals = analysis_result['rsi_signals']
            avg_rsi_bounce = rsi_signals['signal_strength'].mean()
            report += f"RSI反弹平均强度: {avg_rsi_bounce:.2f}\n"
        
        if divergence_count > 0:
            divergence_signals = analysis_result['divergence_signals']
            avg_div_strength = sum(div['divergence_strength'] for div in divergence_signals) / len(divergence_signals)
            report += f"底背离平均强度: {avg_div_strength:.2f}\n"
        
        report += f"\n================= 投资建议 =================\n"
        
        if combined_count > 0:
            report += f"🎯 发现 {combined_count} 个强烈买入信号（RSI反弹+底背离组合）\n"
            report += "   建议: 密切关注这些时间点，考虑分批建仓\n"
        
        if rsi_count > 0 or divergence_count > 0:
            total_signals = rsi_count + divergence_count
            signal_density = total_signals / period_days
            
            if signal_density > 0.5:
                report += "📈 信号密度较高，市场波动性强，适合短线操作\n"
            elif signal_density > 0.2:
                report += "📊 信号密度适中，可考虑中短线策略\n"
            else:
                report += "📉 信号密度较低，建议长线持有或等待更多确认\n"
        else:
            report += "⚠️  当前周期内未发现明确的买入信号\n"
            report += "   建议: 继续观望或调整分析参数\n"
        
        report += f"\n================= 风险提示 =================\n"
        report += "1. 技术分析信号仅供参考，不构成投资建议\n"
        report += "2. 建议结合基本面分析和市场环境判断\n"
        report += "3. 严格执行止损策略，控制风险\n"
        report += "4. 分批建仓，避免单点进入\n"
        
        report += "=" * 50
        
        return report
    
    def analyze_symbol_combined(self,
                              data: pd.DataFrame,
                              symbol: str,
                              period_days: int = 30,
                              price_column: str = 'close',
                              interval: str = '4h',
                              create_charts: bool = True,
                              save_chart: bool = True,
                              save_data: bool = True,
                              output_dir: str = "output") -> Dict:
        """
        执行单个交易对的综合技术分析
        
        Args:
            data: 价格数据DataFrame
            symbol: 交易对符号
            period_days: 分析周期天数
            price_column: 价格列名
            interval: K线间隔，用于动态调整组合信号容忍度
            create_charts: 是否创建图表（影响性能）
            save_chart: 是否保存图表
            save_data: 是否保存分析数据
            output_dir: 输出目录
            
        Returns:
            综合分析结果字典
        """
        logger.info(f"开始对 {symbol} 执行综合技术分析...")
        
        # 执行综合分析
        analysis_result = self.analyze_combined_signals(data, price_column, interval)
        
        # 生成报告
        report = self.generate_combined_report(analysis_result, symbol, period_days)
        
        # 创建可视化（仅在需要时）
        if create_charts and save_chart:
            chart_path = os.path.join(output_dir, f"{symbol}_combined_analysis.png")
            self.create_combined_visualization(analysis_result, symbol, price_column, chart_path)
        
        # 保存分析数据
        if save_data:
            saved_files = self.save_analysis_data(analysis_result, symbol, period_days, output_dir)
            analysis_result['saved_files'] = saved_files
            
            print(f"\n💾 数据保存摘要:")
            print(f"   保存目录: {output_dir}")
            print(f"   保存文件数: {len(saved_files)}")
            for file_type, file_path in saved_files.items():
                print(f"   {file_type}: {os.path.basename(file_path)}")
        
        # 打印报告
        print(report)
        
        # 添加报告到结果中
        analysis_result['report'] = report
        analysis_result['symbol'] = symbol
        
        return analysis_result
